#include <stdio.h>
#include <string.h>

#include "Lexer.h"
#include "Token.h"
#include "vm.h"
#include "Parser.h"

#define MAX_LINE_LEN 999
char LineBuf[MAX_LINE_LEN];

int main()
{
    char currFileName[] = "__CURR__.BAS";
    FILE *loadFile = NULL;
    FILE *saveFile = NULL;
    FILE *currFile = fopen(currFileName, "w");
    const int MAX_CMD_LENGTH = 20;
    const int MAX_FILENAME_LENGTH = 50;
    char cmd[MAX_CMD_LENGTH];

    // clear file
    fclose(currFile);
    currFile = fopen(currFileName, "r+");

    printf(">> ");
    while (scanf("%s", cmd) != EOF)
    {        
        if (!strcmp(cmd, "OLD"))
        {
            char fileName[MAX_FILENAME_LENGTH];
            if (scanf("%s", fileName) != EOF)
            {
                loadFile = fopen(fileName, "r");
                // copy to current file
                while (fgets(LineBuf, MAX_LINE_LEN, loadFile))
                {
                    fputs(LineBuf, currFile);
                }
                fclose(loadFile);
            }
        }
        else if (!strcmp(cmd, "LIST"))
        {
            rewind(currFile);            
            while (fgets(LineBuf, MAX_LINE_LEN, currFile))
            {
                fputs(LineBuf, stdout);
            }
            printf("\n");            
        }
        else if (!strcmp(cmd, "RUN"))
        {
            rewind(currFile);
            Lexer lexer(currFile);
            vm env;
            Parser parser(&lexer, &env);

            parser.Program();
            parser.Run();
        }
        else if (!strcmp(cmd, "NEW"))
        {
            // clear file
            fclose(currFile);
            currFile = fopen(currFileName, "w");
            fclose(currFile);
            currFile = fopen(currFileName, "r+");
        }
        else if (!strcmp(cmd, "SAVE"))
        {
            rewind(currFile);
            char fileName[MAX_FILENAME_LENGTH];
            if (scanf("%s", fileName) != EOF)
            {
                saveFile = fopen(fileName, "w");
                // copy to current file
                while (fgets(LineBuf, MAX_LINE_LEN, currFile))
                {
                    fputs(LineBuf, saveFile);
                }
                fclose(saveFile);
            }
        }
        else if (!strcmp(cmd, "BYE"))
        {
            break;
        }
        else if (atoi(cmd) != 0)
        {            
            fputs(cmd, currFile);
            fgets(LineBuf, MAX_LINE_LEN, stdin);
            fputs(LineBuf, currFile);            
        }
        else
        {
            printf("Unknown Command.\n");
        }
        printf(">> ");
    }
    
    return 0;
}